package com.reggie.controller.admin;

import com.reggie.constant.MessageConstant;
import com.reggie.result.R;
import com.reggie.utils.AliOSSUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;


@Slf4j
@RestController
@RequestMapping("/admin/common")
@Api(tags = "公共接口模块")
public class CommonController {

    @Autowired
    private AliOSSUtil aliOSSUtil;

    @PostMapping("/upload")
    @ApiOperation("文件上传接口")
    public R<String> upload(MultipartFile file){
        log.info("开启文件上传: {}" + file);

        //获取文件的后缀名
        String filename = file.getOriginalFilename();
        String extension = filename.substring(filename.lastIndexOf("."));

        //设置上传后文件的名称
        String fileName = UUID.randomUUID().toString() + extension;

        String upload = "";
        //调用AliOSSUtil工具类上传
        try {
            //获取文件访问地址
            upload = aliOSSUtil.upload(file.getBytes(), fileName);
            return R.success(upload);
        } catch (IOException e) {
            log.error("文件上传失败：" + e.getMessage());
        }
        return R.error(MessageConstant.UPLOAD_FAILED);
    }
}
